<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useHomeStore } from '@/stores/homeStore'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  DataLine,
  Timer,
  Stopwatch,
  Platform,
  Warning,
  Histogram,
  ChatLineRound,
  CaretTop,
  CaretBottom,
  Aim,
  Connection,
  ArrowLeft,
  ArrowRight,
  Loading,
  Download,
  List,
  DataAnalysis
} from '@element-plus/icons-vue'

// 导入图表组件
import SentimentPieChart from '@/components/sentiment/SentimentPieChart.vue'
import SentimentTrendChart from '@/components/sentiment/SentimentTrendChart.vue'
import KeywordCloudChart from '@/components/keywords/KeywordCloudChart.vue'
import PlatformBarChart from '@/components/platform/PlatformBarChart.vue'
import SentimentScatterChart from '@/components/sentiment/SentimentScatterChart.vue'
import HotSentiments from '@/components/HotSentiments.vue'

// 获取首页数据状态
const homeStore = useHomeStore()

// 刷新间隔选项
const refreshIntervals = [
  { label: '10秒', value: 10000 },
  { label: '30秒', value: 30000 },
  { label: '1分钟', value: 60000 },
  { label: '5分钟', value: 300000 }
]
const selectedInterval = ref(60000) // 默认1分钟

// 时间筛选选项
const timeRanges = [
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '自定义', value: 'custom' }
]
const selectedTimeRange = ref('today')
const dateRange = ref([])

// 监控目标索引
const targetIndex = ref(0)
const targetTimer = ref(null as any)

// 活跃平台状态
const activePlatforms = ref<Record<string, boolean>>({})

// 格式化监控目标数据，添加默认值
const formattedPriorityTargets = computed(() => {
  if (!homeStore.priorityTargets || homeStore.priorityTargets.length === 0) return []
  
  return homeStore.priorityTargets.map(target => ({
    ...target,
    count: target.count || 0,
    sentiment: target.sentiment || 0,
    firstSeen: target.firstSeen || '未知',
    attention: target.attention || 50
  }))
})

// 是否有监控目标
const hasTargets = computed(() => {
  return formattedPriorityTargets.value.length > 0
})

// 为界面元素定义本地状态
const chartLoading = ref(false)
const chartUpdateTime = ref('')

// 调试用的计算属性
const debugSentimentTrend = computed(() => {
  console.log('情感趋势数据:', homeStore.sentimentTrend)
  if (!homeStore.sentimentTrend || homeStore.sentimentTrend.length === 0) {
    // 如果没有数据，提供模拟数据
    const mockTrend = [];
    for (let i = 0; i < 24; i++) {
      mockTrend.push({
        date: `${i.toString().padStart(2, '0')}:00`,
        positive: Math.floor(Math.random() * 5) + 1,
        neutral: Math.floor(Math.random() * 3) + 1, 
        negative: Math.floor(Math.random() * 4) + 1
      });
    }
    return mockTrend;
  }
  return homeStore.sentimentTrend
})

// 平台筛选相关的计算属性
const filteredPlatformData = computed(() => homeStore.filteredPlatformComparison)
const filteredHotSentiments = computed(() => homeStore.filteredHotSentiments)

// 计算散点图数据，确保有回退方案
const scatterChartData = computed(() => {
  if (!homeStore.sentimentTimeDistribution || homeStore.sentimentTimeDistribution.length === 0) {
    // 提供模拟散点数据
    const mockScatterData = [];
    for (let i = 0; i < 100; i++) {
      const hour = Math.floor(Math.random() * 24);
      const minute = Math.floor(Math.random() * 60);
      const sentimentValue = (Math.random() * 2 - 1).toFixed(2); // -1.0 到 1.0 之间的随机值
      
      mockScatterData.push({
        id: i + 1,
        time: `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`,
        value: parseFloat(sentimentValue)
      });
    }
    return mockScatterData;
  }
  return homeStore.sentimentTimeDistribution;
})

// 热门关键词数据，确保有回退方案
const keywordCloudData = computed(() => {
  if (!homeStore.hotKeywords || homeStore.hotKeywords.length === 0) {
    // 提供模拟词云数据
    return [
      { word: '人工智能', weight: 95 },
      { word: '数据安全', weight: 87 },
      { word: '疫情防控', weight: 82 },
      { word: '数字经济', weight: 78 },
      { word: '远程办公', weight: 76 },
      { word: '元宇宙', weight: 72 },
      { word: '芯片短缺', weight: 68 },
      { word: '网络安全', weight: 65 },
      { word: '区块链', weight: 62 },
      { word: '大数据', weight: 58 }
    ];
  }
  return homeStore.hotKeywords;
})

// 生命周期钩子
onMounted(async () => {
  try {
    await homeStore.fetchHomeData()
    homeStore.startAutoRefresh()
    
    // 启动监控目标轮播
    startTargetCarousel()
  } catch (error) {
    ElMessage.error('获取数据失败，请检查网络连接')
  }
})

onUnmounted(() => {
  homeStore.stopAutoRefresh()
  stopTargetCarousel()
})

// 手动刷新数据
const refreshData = async () => {
  chartLoading.value = true
  try {
    await homeStore.refresh()
    ElMessage.success('数据已更新')
  } catch (error) {
    ElMessage.error('刷新数据失败')
  }
  chartLoading.value = false
  chartUpdateTime.value = new Date().toLocaleTimeString()
}

// 切换自动刷新
const toggleAutoRefresh = () => {
  if (homeStore.autoRefresh) {
    homeStore.stopAutoRefresh()
    ElMessage.info('已停止自动刷新')
  } else {
    homeStore.startAutoRefresh()
    ElMessage.success('已开启自动刷新')
  }
}

// 更改刷新间隔
const changeRefreshInterval = (interval: number) => {
  homeStore.setRefreshInterval(interval)
  ElMessage.success(`刷新间隔已设置为${interval / 1000}秒`)
}

// 监控目标轮播
const startTargetCarousel = () => {
  targetTimer.value = setInterval(() => {
    if (formattedPriorityTargets.value.length > 0) {
      targetIndex.value = (targetIndex.value + 1) % formattedPriorityTargets.value.length
    }
  }, 3000)
}

const stopTargetCarousel = () => {
  if (targetTimer.value) {
    clearInterval(targetTimer.value)
    targetTimer.value = null
  }
}

// 获取情感类型对应的样式类
const getSentimentClass = (type: number) => {
  switch (type) {
    case 1:
      return 'positive'
    case -1:
      return 'negative'
    default:
      return 'neutral'
  }
}

// 格式化数字，添加千位分隔符
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 处理平台状态变更
const handlePlatformStatusChange = (platforms: Record<string, boolean>) => {
  // 更新store中的平台状态
  homeStore.updateActivePlatforms(platforms)
  
  console.log('平台状态已更新:', platforms)
}

// 手动控制目标切换
const previousTarget = () => {
  if (formattedPriorityTargets.value.length > 0) {
    targetIndex.value = (targetIndex.value - 1 + formattedPriorityTargets.value.length) % formattedPriorityTargets.value.length;
  }
}

const nextTarget = () => {
  if (formattedPriorityTargets.value.length > 0) {
    targetIndex.value = (targetIndex.value + 1) % formattedPriorityTargets.value.length;
  }
}

// 底部操作栏
const exportData = (command: string) => {
  // 实现导出数据的逻辑
  console.log('导出数据:', command)
  
  // 根据不同时间范围导出不同数据
  let exportData: any = {};
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const filename = `sentiment_data_${command}_${timestamp}.json`;
  
  // 构建导出数据
  exportData = {
    meta: {
      exportTime: new Date().toISOString(),
      dataRange: command,
      lastUpdate: homeStore.formattedLastUpdate
    },
    statistics: {
      todayTotal: homeStore.todayTotal,
      realtimeIncrement: homeStore.realtimeIncrement,
      platformCount: homeStore.platformCount,
      alertCount: homeStore.alertCount,
      alertIncrement: homeStore.alertIncrement
    },
    sentiment: {
      distribution: homeStore.sentimentDistribution,
      percentage: homeStore.sentimentPercentage,
      trend: homeStore.sentimentTrend,
      extremes: homeStore.extremeSentiment,
      timeDistribution: homeStore.sentimentTimeDistribution
    },
    hotData: {
      keywords: homeStore.hotKeywords,
      sentiments: homeStore.hotSentiments
    },
    platforms: {
      comparison: homeStore.platformComparison,
      active: homeStore.activePlatforms
    },
    monitoring: {
      priorityTargets: homeStore.priorityTargets
    },
    system: {
      status: homeStore.systemStatus
    }
  };
  
  // 创建下载
  const jsonStr = JSON.stringify(exportData, null, 2);
  const blob = new Blob([jsonStr], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  
  ElMessage.success(`数据已导出到 ${filename}`);
}

// 对话框
const dialogVisible = ref(false)
const currentDialog = ref('keywords')
const dialogTitle = ref('关键词详情')

// 关键词详情数据
interface KeywordDetail {
  word: string;
  weight: number;
  count: number;
  trend: number;
  platforms: string[];
}

const keywordDetails = ref<KeywordDetail[]>([])

const showHotKeywordsDetail = () => {
  currentDialog.value = 'keywords'
  dialogTitle.value = '热门关键词详情'
  dialogVisible.value = true
  
  // 从热词数据生成详情
  keywordDetails.value = homeStore.hotKeywords.map(keyword => {
    // 生成随机的提及次数和趋势
    const count = Math.round(keyword.weight * 10);
    const trend = Math.round((Math.random() * 40) - 20); // -20%到+20%
    
    // 随机选择1-3个平台
    const allPlatforms = ['微博', '抖音', '知乎', '微信', '今日头条', '小红书', 'bilibili', '快手'];
    const platformCount = Math.floor(Math.random() * 3) + 1;
    const platforms: string[] = [];
    
    for (let i = 0; i < platformCount; i++) {
      const randomIndex = Math.floor(Math.random() * allPlatforms.length);
      const platform = allPlatforms.splice(randomIndex, 1)[0];
      platforms.push(platform);
    }
    
    return {
      word: keyword.word,
      weight: keyword.weight,
      count,
      trend,
      platforms
    };
  });
}

const showSentimentAnalysis = () => {
  currentDialog.value = 'sentiment'
  dialogTitle.value = '情感分析详情'
  dialogVisible.value = true
}

const handleDialogClose = () => {
  dialogVisible.value = false
}

const exportDialogData = () => {
  // 导出当前对话框数据
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const filename = `${currentDialog.value}_${timestamp}.json`;
  
  let data: any = {};
  
  if (currentDialog.value === 'keywords') {
    data = keywordDetails.value;
  } else if (currentDialog.value === 'sentiment') {
    data = {
      distribution: homeStore.sentimentDistribution,
      percentage: homeStore.sentimentPercentage,
      extremes: homeStore.extremeSentiment
    };
  }
  
  // 创建下载
  const jsonStr = JSON.stringify(data, null, 2);
  const blob = new Blob([jsonStr], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  
  ElMessage.success(`数据已导出到 ${filename}`);
}
</script>

<template>
  <main class="home-container">
    <!-- 顶部控制栏 -->
    <div class="control-bar">
      <div class="refresh-controls">
        <el-button 
          :icon="Refresh" 
          :loading="homeStore.loading" 
          @click="refreshData" 
          type="primary"
          size="default"
          :disabled="homeStore.autoRefresh"
          class="refresh-button"
        >
          {{ homeStore.loading ? '加载中...' : '刷新数据' }}
        </el-button>
        <el-switch
          v-model="homeStore.autoRefresh"
          @change="toggleAutoRefresh"
          active-text="自动刷新"
          inactive-text="手动刷新"
          inline-prompt
          class="refresh-switch"
        />
        <el-select
          v-model="selectedInterval"
          @change="changeRefreshInterval"
          size="default"
          placeholder="刷新频率"
          class="interval-select"
        >
          <el-option
            v-for="item in refreshIntervals"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span class="last-update" :class="{'updating': homeStore.loading}">
          <el-icon><Timer /></el-icon>
          最后更新: {{ homeStore.formattedLastUpdate }}
          <span v-if="homeStore.loading" class="loading-dots">...</span>
        </span>
      </div>
      
      <div class="time-filter">
        <el-radio-group v-model="selectedTimeRange" size="default">
          <el-radio-button v-for="item in timeRanges" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio-button>
        </el-radio-group>
        <el-date-picker
          v-if="selectedTimeRange === 'custom'"
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="default"
        />
      </div>
    </div>
    
    <!-- 数据加载中遮罩 -->
    <div v-if="homeStore.loading" class="loading-overlay">
      <div class="loading-spinner">
        <el-icon class="is-loading" :size="30"><Loading /></el-icon>
        <span>数据加载中...</span>
      </div>
    </div>
    
    <!-- 概览卡片 -->
    <el-row :gutter="20" class="info-cards">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="info-card" :body-style="{ 'min-height': '120px' }">
          <template #header>
            <div class="card-header">
              <el-icon><DataLine /></el-icon>
              <span>今日舆情总量</span>
            </div>
          </template>
          <div class="card-value animated">{{ formatNumber(homeStore.todayTotal) }}</div>
          <div class="card-footer">
            <div class="trend" :class="{ 'positive': homeStore.realtimeIncrement > 0, 'negative': homeStore.realtimeIncrement < 0 }">
              <el-icon v-if="homeStore.realtimeIncrement > 0"><CaretTop /></el-icon>
              <el-icon v-else-if="homeStore.realtimeIncrement < 0"><CaretBottom /></el-icon>
              {{ Math.abs(homeStore.realtimeIncrement) }} 条
            </div>
            <div class="description">实时增量</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="info-card" :body-style="{ 'min-height': '120px' }">
          <template #header>
            <div class="card-header">
              <el-icon><Platform /></el-icon>
              <span>已接入平台</span>
            </div>
          </template>
          <div class="card-value animated">{{ homeStore.platformCount }}</div>
          <div class="card-footer">
            <div class="description">数据来源平台</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="info-card" :class="{ 'alert-card': homeStore.hasUnhandledAlert }" :body-style="{ 'min-height': '120px' }">
          <template #header>
            <div class="card-header">
              <el-icon><Warning /></el-icon>
              <span>预警信息</span>
              <el-badge v-if="homeStore.alertCount > 0" :value="homeStore.alertCount" type="danger" />
            </div>
          </template>
          <div class="card-value animated" :class="{'alert-value': homeStore.alertCount > 0}">{{ homeStore.alertCount }}</div>
          <div class="card-footer">
            <div class="trend positive" v-if="homeStore.alertIncrement > 0">
              <el-icon><CaretTop /></el-icon>
              {{ homeStore.alertIncrement }} 条
            </div>
            <div class="description">今日新增</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="info-card" v-if="hasTargets" :body-style="{ 'min-height': '120px' }">
          <template #header>
            <div class="card-header">
              <el-icon><Aim /></el-icon>
              <span>重点监控目标</span>
              <div class="target-nav" v-if="formattedPriorityTargets.length > 1">
                <el-icon class="nav-btn" @click="previousTarget"><ArrowLeft /></el-icon>
                <span>{{ targetIndex + 1 }}/{{ formattedPriorityTargets.length }}</span>
                <el-icon class="nav-btn" @click="nextTarget"><ArrowRight /></el-icon>
              </div>
            </div>
          </template>
          <div class="target-info" v-if="formattedPriorityTargets.length > 0">
            <div class="target-name">{{ formattedPriorityTargets[targetIndex].name }}</div>
            <div class="target-details">
              <div class="detail-item">
                <span class="label">类型:</span>
                <span class="value">{{ formattedPriorityTargets[targetIndex].type }}</span>
              </div>
              <div class="detail-item">
                <span class="label">首次发现:</span>
                <span class="value">{{ formattedPriorityTargets[targetIndex].firstSeen }}</span>
              </div>
              <div class="detail-item">
                <span class="label">关注度:</span>
                <el-progress 
                  :percentage="formattedPriorityTargets[targetIndex].attention" 
                  :color="formattedPriorityTargets[targetIndex].attention > 75 ? '#F56C6C' : '#409EFF'"
                  :stroke-width="8"
                />
              </div>
            </div>
          </div>
        </el-card>
        <el-card shadow="hover" class="info-card" v-else :body-style="{ 'min-height': '120px' }">
          <template #header>
            <div class="card-header">
              <el-icon><Stopwatch /></el-icon>
              <span>系统运行时间</span>
            </div>
          </template>
          <div class="card-value animated">30 天</div>
          <div class="card-footer">
            <div class="description">自2023年10月25日</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 情感分布饼图 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>情感比例</span>
              <el-tag v-if="homeStore.sentimentPercentage.positive > homeStore.sentimentPercentage.negative" type="success" size="small">偏正面</el-tag>
              <el-tag v-else-if="homeStore.sentimentPercentage.positive < homeStore.sentimentPercentage.negative" type="danger" size="small">偏负面</el-tag>
              <el-tag v-else type="info" size="small">中性</el-tag>
            </div>
          </template>
          <div class="sentiment-stats">
            <div class="sentiment-item positive">
              <div class="percent">{{ homeStore.sentimentPercentage.positive }}%</div>
              <div class="label">正面</div>
            </div>
            <div class="sentiment-item neutral">
              <div class="percent">{{ homeStore.sentimentPercentage.neutral }}%</div>
              <div class="label">中性</div>
            </div>
            <div class="sentiment-item negative">
              <div class="percent">{{ homeStore.sentimentPercentage.negative }}%</div>
              <div class="label">负面</div>
            </div>
          </div>
          <div class="chart-wrapper">
            <SentimentPieChart :data="homeStore.sentimentDistribution" />
          </div>
        </el-card>
      </el-col>
      
      <!-- 平台分布柱状图 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>平台分布</span>
            </div>
          </template>
          <div class="chart-wrapper platform-chart">
            <PlatformBarChart 
              :data="filteredPlatformData" 
              @platform-status-change="handlePlatformStatusChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 情感趋势图 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>情感走势</span>
              <div class="time-selector">
                <el-radio-group v-model="selectedTimeRange" size="small">
                  <el-radio-button label="today">24小时</el-radio-button>
                  <el-radio-button label="week">7天</el-radio-button>
                  <el-radio-button label="month">30天</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-wrapper trend-chart">
            <SentimentTrendChart :data="debugSentimentTrend" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 热点分析 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 热门词云 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>热门关键词</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <KeywordCloudChart :data="keywordCloudData" />
          </div>
        </el-card>
      </el-col>
      
      <!-- 热点情感 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>热点舆情</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <HotSentiments :data="filteredHotSentiments" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 其他分析图表 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 情感时间分布 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>情感时间分布</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <SentimentScatterChart :data="scatterChartData" />
          </div>
        </el-card>
      </el-col>
      
      <!-- 系统状态 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>系统状态</span>
            </div>
          </template>
          <div class="system-status">
            <div class="status-item" :class="{'active': homeStore.systemStatus.crawler.status}">
              <div class="status-name">
                <el-icon><Connection /></el-icon>
                爬虫服务
              </div>
              <div class="status-value">
                <el-tag :type="homeStore.systemStatus.crawler.status ? 'success' : 'danger'">
                  {{ homeStore.systemStatus.crawler.status ? '正常' : '异常' }}
                </el-tag>
                <span class="response-time">{{ homeStore.systemStatus.crawler.response_time }}ms</span>
              </div>
            </div>
            
            <div class="status-item" :class="{'active': homeStore.systemStatus.nlp.status}">
              <div class="status-name">
                <el-icon><ChatLineRound /></el-icon>
                NLP服务
              </div>
              <div class="status-value">
                <el-tag :type="homeStore.systemStatus.nlp.status ? 'success' : 'danger'">
                  {{ homeStore.systemStatus.nlp.status ? '正常' : '异常' }}
                </el-tag>
                <span class="response-time">{{ homeStore.systemStatus.nlp.response_time }}ms</span>
              </div>
            </div>
            
            <div class="status-item" :class="{'active': homeStore.systemStatus.api.status}">
              <div class="status-name">
                <el-icon><Histogram /></el-icon>
                API服务
              </div>
              <div class="status-value">
                <el-tag :type="homeStore.systemStatus.api.status ? 'success' : 'danger'">
                  {{ homeStore.systemStatus.api.status ? '正常' : '异常' }}
                </el-tag>
                <span class="response-time">{{ homeStore.systemStatus.api.response_time }}ms</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部操作栏 -->
    <div class="action-bar">
      <el-dropdown @command="exportData" split-button type="primary" size="default">
        <template #default>
          <el-icon class="el-icon--left"><Download /></el-icon>
          导出数据
        </template>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="today">今日数据</el-dropdown-item>
            <el-dropdown-item command="week">本周数据</el-dropdown-item>
            <el-dropdown-item command="month">本月数据</el-dropdown-item>
            <el-dropdown-item command="all" divided>全部数据</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      
      <div class="action-buttons">
        <el-button type="success" plain size="default" @click="showHotKeywordsDetail">
          <el-icon class="el-icon--left"><List /></el-icon>
          关键词详情
        </el-button>
        <el-button type="warning" plain size="default" @click="showSentimentAnalysis">
          <el-icon class="el-icon--left"><DataAnalysis /></el-icon>
          情感分析
        </el-button>
      </div>
    </div>

    <!-- 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :before-close="handleDialogClose"
    >
      <div v-if="currentDialog === 'keywords'" class="dialog-content">
        <el-table :data="keywordDetails" stripe style="width: 100%">
          <el-table-column prop="word" label="关键词" width="180" />
          <el-table-column prop="weight" label="热度" width="100">
            <template #default="scope">
              <el-progress :percentage="Math.round(scope.row.weight)" :format="(percentage: number) => `${scope.row.weight}`" />
            </template>
          </el-table-column>
          <el-table-column prop="count" label="提及次数" width="100" />
          <el-table-column prop="trend" label="趋势" width="120">
            <template #default="scope">
              <span :class="scope.row.trend > 0 ? 'positive' : scope.row.trend < 0 ? 'negative' : 'neutral'">
                <el-icon v-if="scope.row.trend > 0"><CaretTop /></el-icon>
                <el-icon v-else-if="scope.row.trend < 0"><CaretBottom /></el-icon>
                <span>{{ Math.abs(scope.row.trend) }}%</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="platforms" label="主要平台">
            <template #default="scope">
              <el-tag 
                v-for="platform in scope.row.platforms" 
                :key="platform" 
                class="platform-tag"
                size="small"
              >
                {{ platform }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div v-else-if="currentDialog === 'sentiment'" class="dialog-content">
        <div class="sentiment-summary">
          <div class="summary-card positive">
            <div class="summary-title">正面情感</div>
            <div class="summary-value">{{ homeStore.sentimentDistribution.positive }}</div>
            <div class="summary-percent">{{ homeStore.sentimentPercentage.positive }}%</div>
          </div>
          <div class="summary-card neutral">
            <div class="summary-title">中性情感</div>
            <div class="summary-value">{{ homeStore.sentimentDistribution.neutral }}</div>
            <div class="summary-percent">{{ homeStore.sentimentPercentage.neutral }}%</div>
          </div>
          <div class="summary-card negative">
            <div class="summary-title">负面情感</div>
            <div class="summary-value">{{ homeStore.sentimentDistribution.negative }}</div>
            <div class="summary-percent">{{ homeStore.sentimentPercentage.negative }}%</div>
          </div>
        </div>
        
        <div class="sentiment-extremes">
          <h4>情感极值</h4>
          <div class="extremes-container">
            <div class="extreme-item positive" v-if="homeStore.extremeSentiment.most_positive">
              <div class="extreme-title">最积极情感</div>
              <div class="extreme-content">
                <div class="extreme-value">{{ homeStore.extremeSentiment.most_positive.value.toFixed(2) }}</div>
                <div class="extreme-text">{{ homeStore.extremeSentiment.most_positive.title }}</div>
              </div>
            </div>
            
            <div class="extreme-item negative" v-if="homeStore.extremeSentiment.most_negative">
              <div class="extreme-title">最消极情感</div>
              <div class="extreme-content">
                <div class="extreme-value">{{ homeStore.extremeSentiment.most_negative.value.toFixed(2) }}</div>
                <div class="extreme-text">{{ homeStore.extremeSentiment.most_negative.title }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportDialogData">
            <el-icon class="el-icon--left"><Download /></el-icon>
            导出数据
          </el-button>
        </span>
      </template>
    </el-dialog>
  </main>
</template>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
  padding: 20px;
  position: relative;
}

/* 控制栏样式 */
.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--header-bg);
  border-radius: 8px;
  padding: 16px;
  box-shadow: var(--box-shadow);
  width: 100%;
}

.refresh-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.refresh-button {
  font-weight: 500;
}

.refresh-switch {
  margin: 0 10px;
}

.interval-select {
  width: 120px;
}

.last-update {
  color: var(--text-color-secondary);
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.last-update.updating {
  color: #409EFF;
}

.loading-dots {
  animation: loading-dots 1.5s infinite;
  display: inline-block;
  width: 20px;
}

@keyframes loading-dots {
  0% { content: '.'; }
  33% { content: '..'; }
  66% { content: '...'; }
  100% { content: '.'; }
}

.time-filter {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 加载中遮罩样式 */
.loading-overlay {
  position: absolute;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  border-radius: 8px;
  pointer-events: none;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.loading-spinner span {
  color: #606266;
  font-size: 14px;
}

/* 信息卡片样式 */
.info-cards {
  width: 100%;
  margin: 0 !important;
}

.info-card {
  height: 100%;
  background-color: var(--header-bg);
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
  margin-bottom: 20px;
}

.info-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--text-color);
  font-weight: 500;
}

.card-header .el-icon {
  margin-right: 8px;
}

.card-value {
  font-size: 32px;
  font-weight: 600;
  margin: 10px 0;
  color: var(--primary-color);
}

.card-value.animated {
  transition: all 0.3s ease;
}

.card-value.alert-value {
  color: #F56C6C;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.7; }
  100% { opacity: 1; }
}

.card-footer {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-top: 15px;
}

.trend {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.description {
  font-size: 12px;
  color: var(--text-color-secondary);
  margin-top: 5px;
}

.positive {
  color: var(--success-color);
}

.negative {
  color: var(--danger-color);
}

.neutral {
  color: var(--text-color-secondary);
}

/* 目标信息样式 */
.target-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.target-name {
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
}

.target-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-item .label {
  font-size: 14px;
  color: var(--text-color-secondary);
  min-width: 80px;
}

.detail-item .value {
  font-size: 14px;
  font-weight: 500;
}

.target-nav {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 12px;
}

.nav-btn {
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  transition: all 0.2s;
}

.nav-btn:hover {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

/* 情感比例样式 */
.sentiment-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.sentiment-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  min-width: 70px;
}

.sentiment-item.positive {
  background-color: rgba(103, 194, 58, 0.1);
}

.sentiment-item.neutral {
  background-color: rgba(144, 147, 153, 0.1);
}

.sentiment-item.negative {
  background-color: rgba(245, 108, 108, 0.1);
}

.sentiment-item .percent {
  font-size: 20px;
  font-weight: 600;
}

.sentiment-item .label {
  font-size: 12px;
  margin-top: 5px;
}

/* 图表样式 */
.chart-row {
  width: 100%;
  margin: 0 !important;
}

.chart-card {
  height: 100%;
  background-color: var(--header-bg);
  border-radius: 8px;
  transition: box-shadow 0.3s;
  margin-bottom: 20px;
  overflow: visible;
}

.chart-card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.chart-wrapper {
  width: 100%;
  height: 280px;
  overflow: hidden;
}

.platform-chart {
  height: 320px;
}

.trend-chart {
  height: 320px;
}

/* 系统状态样式 */
.system-status {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px 0;
  height: 280px;
  overflow-y: auto;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-radius: 6px;
  background-color: rgba(0, 0, 0, 0.03);
  transition: all 0.3s;
}

.status-item.active {
  background-color: rgba(103, 194, 58, 0.05);
}

.status-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.status-value {
  display: flex;
  align-items: center;
  gap: 10px;
}

.response-time {
  font-size: 13px;
  color: var(--text-color-secondary);
}

/* 时间选择器样式 */
.time-selector {
  display: flex;
  align-items: center;
}

/* 媒体查询，响应式布局 */
@media (max-width: 1200px) {
  .chart-wrapper {
    height: 250px;
  }
  
  .platform-chart {
    height: 300px;
  }
  
  .trend-chart {
    height: 300px;
  }
  
  .sentiment-item {
    padding: 6px 8px;
  }
  
  .sentiment-item .percent {
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .control-bar {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .time-filter {
    width: 100%;
  }
  
  .chart-wrapper {
    height: 220px;
  }
  
  .platform-chart {
    height: 250px;
  }
  
  .trend-chart {
    height: 250px;
  }
}

/* 底部操作栏样式 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: var(--header-bg);
  border-radius: 8px;
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 对话框样式 */
.dialog-content {
  padding: 20px;
}

.sentiment-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.summary-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border-radius: 6px;
  background-color: rgba(0, 0, 0, 0.03);
  width: 30%;
}

.summary-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
}

.summary-percent {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.sentiment-extremes {
  margin-top: 20px;
}

.extremes-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.extreme-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border-radius: 6px;
  background-color: rgba(0, 0, 0, 0.03);
  width: 45%;
}

.extreme-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
}

.extreme-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.extreme-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
}

.extreme-text {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.platform-tag {
  margin-top: 5px;
}
</style> 